from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from .models import GoodsInfo, ShoppingCar
import json

# Create your views here.

def index(request):
    return render(request, 'pos机/main.html')


def goodsList(request):
    return render(request, 'pos机/goodsList.html')


def shoppingCar(request):
    return render(request, 'pos机/shoppingCart.html')


def payView(request):
    return render(request, 'pos机/payPage.html')


def ajax_goodsInfo(request):
    print('------------------')
    request 
    goods = GoodsInfo.objects.all()
    goods = list(goods)
    goodsInfo = []

    for index in range(len(goods)):
        dict = {
            'type': goods[index].type,
            'name': goods[index].name,
            'price': goods[index].price,
            'unit': goods[index].unit,
            'discount': goods[index].discount,
            'id': goods[index].id
        }
        goodsInfo.append(dict)

    response = HttpResponse(json.dumps(goodsInfo))
    response["Access-Control-Allow-Origin"] = "*"
    response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    response["Access-Control-Max-Age"] = "1000"
    response["Access-Control-Allow-Headers"] = "*"
    return response
    # return JsonResponse(goodsInfo, safe=False)


def ajax_ShoppingCarSave(request):

    if request.method == 'POST':
        getInfo = dict(request.POST)
        addGoodsToCar(getInfo)  
        return HttpResponse('加入购物车成功')

    if request.method == 'GET':
        info = getGoodCarInfo()
        # info = range(100)
        return JsonResponse(info, safe=False)

    if request.method == 'AAA':
        all = ShoppingCar.objects.all()
        all.delete()
        return HttpResponse('删除成功')

    return render(request, 'goodsList.html')




def getGoodCarInfo():
    info = list(ShoppingCar.objects.all())
    infoList = []
    for index in range(len(info)):
        dic = {}
        dic['name'] = info[index].name
        dic['type'] = info[index].type
        dic['price'] = info[index].price
        dic['subtotal'] = info[index].subtotal
        dic['unit'] = info[index].unit
        dic['count'] = info[index].count
        dic['id'] = info[index].id
        dic['discount'] = info[index].discount
        infoList.append(dic)
    return infoList



def addGoodsToCar(goodInfo):
    infoDic = {}
    for key, value in goodInfo.items():
        infoDic[key] = str(value)[2: -2]

    goods = ShoppingCar.objects.all()
    for index in range(len(goods)):
        if str(goods[index]) == infoDic['name']:
            good = ShoppingCar.objects.get(name=infoDic['name'])
            if infoDic['change'] == 'true':
                good.count = int(infoDic['compute'])
            else:
                good.count += int(infoDic['compute'])
            good.save()
            good.subtotal = getSubtotal(good)
            good.save()
            if good.count==0: 
                good.delete()
            return True
    subtotal = infoDic['price'] + '元'
    ShoppingCar.objects.create(type=infoDic['type'], name=infoDic['name'], id=int(infoDic['id']), price=infoDic['price'], unit=infoDic['unit'], discount=transBoolFormat(infoDic['discount']), count=1, subtotal=subtotal)



def getSubtotal(good):
    number = good.count
    price = number * float(good.price)
    if number > 2 and good.discount==True:
        number = number - number // 3
        realPrice = number * float(good.price)
        return str(realPrice) + "元(原价：" + str(price) + "元)"
    else:
        return str(price) + "元"



def transBoolFormat(data):
    if data == 'false':
        return False
    if data == 'true':
        return True


